<script setup lang="ts">
import type { CustomDialogInstance, EquipmentDefinition } from '@/types'

import VueDraggable from 'vuedraggable'
import type { EfficiencyConfig, SaveEfficiencyParams } from '../type'
import { EFFICIENCY_LOCATION } from '../constant'
import { STORAGE_MODES } from '@/enum/modules/indicator'

defineOptions({
  name: 'LeftSettingPanel',
})

const props = defineProps<{
  equipmentId: number | string
  options: EquipmentDefinition[]
  oldList: EfficiencyConfig[]
}>()

const emit = defineEmits<{
  (e: 'open'): void
  (e: 'close'): void
  (e: 'saveSuccess'): void
}>()

const dialogRef = ref<CustomDialogInstance>()
const modalTitle = computed(() => {
  return `左侧数据设置${list.value.length}/6`
})
const title = ref()
const definitionInfoId = ref()
const options = computed(() => {
  const data = unref(list)
  return props.options.map((v) => {
    return {
      label: v.name,
      value: v.id!,
      disabled: data.some(vv => vv.definitionInfoId === v.id),
    }
  })
})
const list = ref<{
  _uuid: string
  name: string
  definitionInfoName: string
  definitionInfoId: number
}[]>([])

function getDefinitionInfoName(id: number) {
  return options.value.find(v => v.value === id)?.label ?? ''
}

async function handleAdd() {
  const id = unref(definitionInfoId)
  if (id) {
    if (list.value.every(v => v.definitionInfoId !== id)) {
      list.value.push({
        _uuid: uuid(),
        name: getDefinitionInfoName(id),
        definitionInfoId: id,
        definitionInfoName: getDefinitionInfoName(id),
      })
    }
    else {
      ElMessage.warning('该技术参数已存在')
    }
  }
  else {
    ElMessage.warning('请选择技术参数')
  }
}
async function handleRemove(item: any) {
  const index = list.value.findIndex(v => v.definitionInfoId === item.definitionInfoId)
  if (index > -1) {
    list.value.splice(index, 1)
  }
}

async function clickSave(done: () => void) {
  const params: SaveEfficiencyParams = {
    equipmentId: +unref(props.equipmentId),
    location: EFFICIENCY_LOCATION.LEFT,
    list: unref(list).map((v) => {
      return {
        equipmentId: +unref(props.equipmentId),
        definitionInfoId: v.definitionInfoId,
        location: EFFICIENCY_LOCATION.LEFT,
        title: unref(title),
        dataName: v.name,
        dataValue: getDefinitionInfoName(v.definitionInfoId),
        timeType: STORAGE_MODES.NOW,
      }
    }),
  }
  if (!unref(title)) {
    done()
    return ElMessage.warning('请输入标题')
  }
  if (list.value.length === 0) {
    done()
    return ElMessage.warning('请选择技术参数并增加数据')
  }
  try {
    await equipmentEfficiencyApi.saveEquipmentEfficiencyConfigData(params)
    ElMessage.success('保存成功')
    done()
    close()
    emit('saveSuccess')
  }
  finally {
    done()
  }
}

async function open() {
  dialogRef.value?.open()
  emit('open')
}
async function close() {
  dialogRef.value?.close()
  emit('close')
}

watch(() => props.equipmentId, () => {
  title.value = ''
  definitionInfoId.value = undefined
})

watchEffect(() => {
  title.value = unref(props.oldList)[0]?.title ?? ''
  list.value = unref(props.oldList).map(v => ({
    _uuid: uuid(),
    name: v.dataName ?? '',
    definitionInfoId: v.definitionInfoId,
    definitionInfoName: v.dataValue,
  }))
})

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="modalTitle"
    width="640px"
    need-saving
    @confirm="clickSave"
  >
    <div class="flex items-center p-3">
      <span class="required flex-shrink-0 opacity-80">标题名称：</span>
      <ElInput v-model.trim="title" class="flex-auto" placeholder="请输入标题名称" />
    </div>
    <div class="flex items-center p-3">
      <span class="flex-shrink-0 opacity-80">技术参数：</span>
      <ElSelect v-model="definitionInfoId" class="!w-1/2" placeholder="请选择技术参数">
        <ElOption v-for="item in options" :key="item.value" v-bind="item" />
      </ElSelect>
      <ElButton class="ml-3" type="success" @click="handleAdd">
        新增数据
      </ElButton>
    </div>
    <div class="p-3">
      <VueDraggable
        :list="list" item-key="_uuid"
        ghost-class="ghost"
        chosen-class="chosenClass"
      >
        <template #item="{ element }">
          <div class="item move alpha-block mb-3 flex cursor-move items-center">
            <div class="flex-auto">
              <div class="flex items-center border-b border-gray-200 p-3">
                <span class="flex-shrink-0 opacity-80">数据名称：</span>
                <ElInput v-model="element.name" class="flex-auto" placeholder="请输入参数名称" />
              </div>
              <div class="flex items-center border-b border-gray-200 p-3">
                <span class="flex-shrink-0 opacity-80">技术参数：</span>
                <span>{{ element.definitionInfoName }}</span>
              </div>
            </div>
            <div class="flex-shrink-0 px-3">
              <ElButton type="danger" @click="handleRemove(element)">
                移除
              </ElButton>
            </div>
          </div>
        </template>
      </VueDraggable>
    </div>
  </CustomDialog>
</template>

<style scopeds>
.required:before {
  content: '*';
  margin-right: 4px;
  color: rgb(254, 107, 107);
}
.chosenClass {
  border: solid 1px rgb(167, 20, 56);
}
</style>
